package com.icesoft.core.web.configurer.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.xbill.DNS.Address;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Set;

@Component
@ConditionalOnProperty(name = AdminServerIpHelper.ADMIN_SERVER_URL_PROPERTY)
@ConditionalOnClass(name = "de.codecentric.boot.admin.client.config.ClientProperties")
@Slf4j
public class AdminServerIpHelper {

	static final String ADMIN_SERVER_URL_PROPERTY = "spring.boot.admin.client.url";
	private final Set<String> ips = new HashSet<>();

	@Value("${" + ADMIN_SERVER_URL_PROPERTY + "}")
	private String serverUrl;

	private final Object lock = new Object();

	private static final long timeout = 14400 * 1000;
	private long lastTimestamp = 0;

	private boolean needRefresh() {
		return ips.isEmpty() || System.currentTimeMillis() - lastTimestamp > timeout;
	}

	public Set<String> getAdminServerIps() {
		if (needRefresh()) {
			synchronized (lock) {
				if (!needRefresh()) {
					return ips;
				}
				String name = getName(serverUrl);
				try {
					for (InetAddress address : Address.getAllByName(name)) {
						ips.add(address.getHostAddress());
					}
					lastTimestamp = System.currentTimeMillis();
					log.info("获取admin server IP地址成功：{}", ips);
				} catch (UnknownHostException e) {
					log.error("获取IP地址失败，serverUrl={},name={}", serverUrl, name);
				}
			}

		}
		return ips;
	}

	private static String getName(String url) {
		String name = url.replaceFirst("http://", "").replaceFirst("https://", "");
		int idx1 = name.indexOf(":"), idx2 = name.indexOf("/");
		int endIndex = idx1 > 0 ? idx1 : idx2 > 0 ? idx2 : name.length();
		name = name.substring(0, endIndex);
		return name;
	}

}
